<template>
    <el-scrollbar ref="myScrollbar" style="overflow-x: hidden">
        <div class="record_list_cls">
            <record-item v-for="(t,i) in finalRecords" :key="i"
                         :record="t"
                         @deal-invitation="dealInvitation"
            ></record-item>
        </div>
    </el-scrollbar>
</template>

<script>
  import _g from '../../assets/utils/global'
  import * as _ from 'underscore'
  import _subject from '../../assets/utils/subject'
  import RecordItem from './RecordItem'
  import comm from '../../assets/utils/comm'

  export default {
    name: 'RecordList',
    props: {
      who: {
        type: String,
        default: '1'
      },
      side: {
        type: String,
        default: 'talent'
      },
      commId: {
        type: Number,
        default: 0
      },
      toId: {
        type: Number,
        default: 0
      },
      jrrId: {
        type: Number,
        default: 0
      },
      createTime: {
        type: Number,
        default: 0
      },
      decidedQ: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      finalRecords() {
        this.judgeShowTime()
        return this.communication.records
      }
    },
    watch: {
      commId: {
        immediate: true,
        handler() {
          console.log('person changed ', this.commId, this.toId, this.jrrId)
          if (this.commId) {
            //重新开始分页
            this.page.current = 0
            this.communication.records.splice(0, this.communication.records.length)
            console.log('change record list')
            this.loadRecords()
          }
        }
      },
      decidedQ: {
        immediate: true,
        handler(n) {
          this.deal = n
        }
      }
    },
    methods: {
      dealInvitation(s) {
        let state = 0
        let msg = ''
        if (s === 'accept') {
          state = 3
          msg = '接受'
        } else if (s === 'reject') {
          state = 2
          msg = '拒绝'
        }
        if (state) {
          //请求服务器数据接收或者拒绝该职位
          _g.apiPost('/talent/invitationInduction.do', { jrrId: this.jrrId, state: state })
            .then(res => {
              if (res && res.status === 0) {
                _g.message('处理邀请成功', 'success')
                //本地记录添加消息
                this.sendContent(msg, 1)
                this.deal = true
                //置灰该条消息记录
                let exit = _.find(this.communication.records, t => {
                  return Number(t.type) === 2
                })
                if (exit) {
                  exit.decidedQ = true
                }
              }
            })
        }
      },
      getNewMessage(commId, unread) {
        this.$emit('new-msg', commId, unread)
      },
      scrollDown() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      scrollPercent() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight - this.page.lastHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      onScrollTop() {
        console.log('reach top')
        this.loadRecords()
      },
      judgeShowTime() {
        //是否显示时间，3min以内的时间不显示
        for (let i = 1; i < this.communication.records.length; i++) {
          const last = this.communication.records[i - 1]
          const current = this.communication.records[i]
          // console.log('show time', last.time, current.time)
          current.showTimeQ = current.time - last.time > 3 * 60 * 1000
        }
        //头像
        _.each(this.communication.records, t => {
          t.icon = t.meQ ? _subject.getTalentIcon() : comm.toIcon
        })
      },
      getSysMsg(type, text) {
        if (type === 1) {
          switch (text) {
            case '拒绝':
              return '您已拒绝您的入职邀请'
            case '接受':
              return '您已接受您的入职邀请'
            case '已将对方简历标记为不合适':
              return '您的简历已被标记为不合适'
          }
        }
        return text
      },
      loadRecords() {
        _g.apiPost('/talent/selectComDetailInfoByTalent.do', {
          comID: this.commId,
          state: Number(this.who),
          currPageNo: this.page.current + 1,
          pageSize: this.page.size
        }).then(res => {
          if (res && res.status === 0) {
            const page = res.data.pageInfo
            this.page.total = page.total
            this.page.current = page.pageNum
            console.log('communication page info', page, this.page)
            if (page.list.length > 0) {
              let temp = []
              _.each(page.list, t => {
                const o = JSON.parse(t.content)
                const state = Number(o.send_state)
                const content = this.getSysMsg(state, o.content)
                const time = Date.parse(t.time)
                temp.push({
                  showTimeQ: false,
                  meQ: o.mainCom === this.side,
                  content: content,
                  type: state,
                  time: time,
                  hello: state === 6 ? content : {},
                  decidedQ: state === 2 ? this.deal : false
                })
              })
              console.log('filter', temp, this.decidedQ)
              temp = _.sortBy(temp, t => {
                return t.time
              })
              if (this.page.current === 1) {
                this.communication.records = temp
                this.scrollDown()
              } else {
                this.communication.records = temp.concat(this.communication.records)
                this.scrollPercent()
              }
            } else {
              this.page.current -= 1
            }
          }
        })
      },
      sendContent(text, type) {
        console.log('talent id', this.toId)
        const str = {
          'toCom': this.who === '1' ? 'platform' : 'company',
          'toUserId': String(this.toId),
          'comid': String(this.commId),
          'type': 'SINGLE_SENDING',
          'content': text,
          'mainUserId': _subject.getTalentId(),
          'mainCom': this.side,
          'send_state': String(type)
        }
        console.log('send ws', str)
        _subject.ws.next(str)
        //添加到本地记录
        let content = this.getSysMsg(type, text)
        this.communication.records.push({
          type: type,
          content: content,
          meQ: true,
          time: new Date().format('yyyy-MM-dd hh:mm:ss'),
          hello: type === 6 ? content : {}
        })
        this.scrollDown()
      },
      sendText(currentInput) {
        const trim = currentInput.trim()
        if (trim) {
          this.sendContent(trim.replace(/\n/g, '<br/>'), 0)
        }
      }
    }
    ,
    data() {
      return {
        data: '',
        wsSub: null,
        page: {
          current: 0,
          size: 10,
          total: 0,
          lastHeight: 0//加载新页之前scrollbar的高度
        },
        communication: {
          records: [
            // { meQ: true, type: 0, content: 'abc' },
          ]
        },
        deal: false
      }
    }
    ,
    components: {
      RecordItem
    }
    ,
    created() {
      //订阅服务器的消息
      let self = this
      console.log('subscribe================')
      this.wsSub = _subject.ws.subscribe({
        next(t) {
          console.log('raw ws', t)
          if (t.status === 200) {
            console.log(200)
            let m = t.data.type
            if (m === 'SINGLE_SENDING') {
              let commId = t.data.comid
              let mainId = t.data.mainUserId
              let toId = t.data.toUserId//对方发送的消息
              //通知收到父组件消息
              console.log('new message')
              self.getNewMessage(Number(t.data.comid), Number(t.data.unread))
              // if (commId === String(self.commId) && toId === String(_subject.getTalentId()) && mainId === String(self.toId)) {
              if (commId === String(self.commId)) {
                const type = Number(t.data.send_state)
                const content = self.getSysMsg(type, t.data.content)
                self.communication.records.push({
                  type: type,
                  content: content,
                  meQ: false,
                  time: new Date().format('yyyy-MM-dd hh:mm:ss'),
                  hello: type === 6 ? content : {},
                  decidedQ: false
                })
              }
              self.scrollDown()
            }
          } else if (t.status === -1) {
            _g.message('对方不在线，可能无法立即回复您', 'warning')
          }
        }
      })
    }
    ,
    destroyed() {
      console.log('unsubscribe================')
      if (this.wsSub) {
        this.wsSub.unsubscribe()
      }
    }
    ,
    mounted() {
      this.$refs['myScrollbar'].wrap.onscroll = e => {
        if (e.target.scrollTop === 0) {
          this.onScrollTop()
        }
      }
    }
  }
</script>

<style scoped>

</style>